<template>
  <div class="product-detail">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />
    
    <!-- 加载状态 -->
    <van-loading v-if="loading" class="loading" />
    
    <!-- 商品内容 -->
    <template v-else>
      <!-- 商品图片轮播 -->
      <van-swipe class="product-images" :autoplay="3000">
        <van-swipe-item v-for="(image, index) in product.images" :key="index">
          <img :src="image" :alt="product.name" />
        </van-swipe-item>
      </van-swipe>

      <!-- 商品信息 -->
      <div class="product-info">
        <h1 class="product-name">{{ product.name }}</h1>
        <div class="price-info">
          <span class="group-buy-price">¥{{ product.groupBuyPrice }}</span>
          <span class="original-price">¥{{ product.originalPrice }}</span>
          <span class="discount">{{ product.discount }}折</span>
        </div>
        <div class="store-info">
          <van-icon name="location-o" />
          <span>{{ product.storeName }}</span>
        </div>
      </div>

      <!-- 拼购进度 -->
      <div class="group-buy-progress">
        <div class="progress-header">
          <span>拼购进度</span>
          <span class="progress-text">已拼{{ groupBuy.soldShares }}/{{ groupBuy.totalShares }}</span>
        </div>
        <van-progress :percentage="progressPercentage" :show-pivot="false" />
        <div class="time-remaining">
          <van-icon name="clock-o" />
          <span>剩余时间：{{ timeRemaining }}</span>
        </div>
      </div>

      <!-- 商品详情 -->
      <div class="product-description">
        <h3>商品详情</h3>
        <p>{{ product.description }}</p>
        
        <!-- 商品图片展示 -->
        <div class="product-images-section">
          <h4>商品图片</h4>
          <div class="images-grid">
            <div 
              v-for="(image, index) in product.images" 
              :key="index" 
              class="image-item"
              @click="previewImage(index)"
            >
              <img :src="image" :alt="`${product.name} - 图片${index + 1}`" />
            </div>
          </div>
        </div>
      </div>

      <!-- 底部购买按钮 -->
      <div class="bottom-bar">
        <van-button type="primary" size="large" @click="joinGroupBuy">
          立即拼购
        </van-button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()

// 加载状态
const loading = ref(true)

// 商品数据
const product = ref({
  id: 0,
  name: '',
  images: [],
  originalPrice: 0,
  groupBuyPrice: 0,
  discount: 0,
  storeName: '',
  description: ''
})

// 拼购数据
const groupBuy = ref({
  id: 0,
  soldShares: 0,
  totalShares: 0,
  startTime: new Date(),
  duration: 24 * 60 * 60 * 1000 // 24小时
})

// 计算进度百分比
const progressPercentage = computed(() => {
  if (groupBuy.value.totalShares === 0) return 0
  return Math.round((groupBuy.value.soldShares / groupBuy.value.totalShares) * 100)
})

// 计算剩余时间
const timeRemaining = computed(() => {
  const startTime = new Date(groupBuy.value.startTime)
  const endTime = new Date(startTime.getTime() + groupBuy.value.duration)
  const now = new Date()
  const diff = endTime.getTime() - now.getTime()
  
  if (diff <= 0) return '已结束'
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  return `${hours}小时${minutes}分钟`
})

// 获取商品详情
const fetchProductDetail = async (productId: string) => {
  try {
    const response = await fetch(`/api/product/${productId}`)
    
    if (!response.ok) {
      throw new Error('获取商品详情失败')
    }
    
    const data = await response.json()
    
    // 更新商品数据
    product.value = {
      id: data.id,
      name: data.name,
      images: data.images || [],
      originalPrice: data.originalPrice,
      groupBuyPrice: data.groupBuyPrice,
      discount: data.discount,
      storeName: data.storeName,
      description: data.description
    }
    
    // 更新拼购数据
    groupBuy.value = {
      id: data.groupBuy.id,
      soldShares: data.groupBuy.soldShares,
      totalShares: data.groupBuy.totalShares,
      startTime: new Date(data.groupBuy.startTime),
      duration: data.groupBuy.duration
    }
    
  } catch (error) {
    console.error('获取商品详情错误:', error)
    showToast('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 参与拼购
const joinGroupBuy = () => {
  router.push(`/groupbuy/${groupBuy.value.id}`)
}

// 预览图片
const previewImage = (index: number) => {
  // 简单的图片预览，直接在新窗口打开
  window.open(product.value.images[index], '_blank')
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  // 根据路由参数获取商品详情
  const productId = route.params.id as string
  if (productId) {
    fetchProductDetail(productId)
  } else {
    showToast('商品ID无效')
    loading.value = false
  }
})
</script>

<style scoped>
.product-detail {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120px; /* 增加底部间距，避免被固定按钮遮挡 */
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.product-images {
  height: 300px;
}

.product-images img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  background: white;
  padding: 20px;
  margin-bottom: 10px;
}

.product-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.group-buy-price {
  color: #ff6b6b;
  font-size: 24px;
  font-weight: bold;
}

.original-price {
  color: #999;
  text-decoration: line-through;
}

.discount {
  background: #ff6b6b;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.store-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.group-buy-progress {
  background: white;
  padding: 20px;
  margin-bottom: 10px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.progress-text {
  color: #666;
  font-size: 14px;
}

.time-remaining {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.product-description {
  background: white;
  padding: 20px;
  margin-bottom: 20px; /* 添加底部间距 */
}

.product-description h3 {
  margin-bottom: 10px;
}

.bottom-bar {
  position: fixed;
  bottom: 0; /* 详情页面没有Tabbar，直接贴底 */
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  border-top: 1px solid #eee;
  z-index: 100;
}

.product-images-section {
  margin-top: 20px;
  margin-bottom: 20px;
}

.product-images-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #333;
}

.images-grid {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.image-item {
  width: 100%;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-item img {
  width: 100%;
  height: auto;
  object-fit: cover;
  display: block;
}
</style> 